<?php


namespace app\api\controller;


use think\Controller;
use think\Db;

class Weixin extends Controller
{
    const appId ='wx00164147ca7b1e60';
    const appSecret ='e503dd6455821324e89ac04a2d6c4268';
    public function getTemplate(){
        $tokenArr = $this->getToken();
        $template = file_get_contents('https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token='.$tokenArr['access_token']);
        print_r($template);
    }
    public function bind(){
        if($this->request->isAjax()){
            $mobile = $this->request->param('phone');
            $openid = $this->request->param('openid');
            if($mobile && $openid){
                $user = Db::name('user')->where(['mobile'=>$mobile])->find();
                if($user){
                    if($user['wechat_openid']){
                        $this->error('账号已绑定');
                    }else{
                        Db::name('user')->where(['id'=>$user['id']])->update(['wechat_openid'=>$openid]);
                        $this->success('绑定成功！','',[]);
                    }

                }else{
                    $this->error('绑定账号不存在');
                }

            }else{
                $this->error('绑定失败');
            }
        }else{
            // 判断是否已经获取 code

            if (!isset($_GET['code'])) {
                $domain = $this->request->domain();
                //print_r($domain);exit;
                $redirect_uri = urlencode($domain.'/api/Weixin/bind'); // 替换为你的回调地址
                $scope = 'snsapi_base'; // 静默授权
                $appid =self::appId;

                // 如果没有 code，则跳转到微信授权页面
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";
                header("Location: {$url}");
                exit;
            } else {
                // 获取 code 参数
                $code = $_GET['code'];
                $appSecret = self::appSecret;
                $appid =self::appId;
                // 使用 code 换取 openid

                $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appSecret}&code={$code}&grant_type=authorization_code";
                $response = file_get_contents($token_url);
                $json = json_decode($response, true);

            }
            //$json=['openid'=>'oQ8HH5szLocgW0UjiRIuppMbkcFQ'];
            $this->view->assign("openid", $json['openid']);
            return $this->view->fetch();
        }
    }
    public function test(){
        $tokenArr = $this->getToken();
        $template_id ='prQp8kTltDlDSIV6jhk-D0GmqKmQNPCwuti89g9wd8o';
        $data=[];
        $data['thing7']=["value" =>'恭喜您获得1张会员卡'];
        $data['thing10']=["value" =>'测试充值卡'];
        $data['amount4']=["value" =>'310'];
        $data['time1']=["value" =>'2025-04-25 18:19:35'];
        $data['thing6']=["value" =>'楼小魅总部'];
        $url='';
        $openid ='oQ8HH5szLocgW0UjiRIuppMbkcFQ';
        $this->sendTemplateMessage($tokenArr['access_token'],$openid, $template_id, $data, $url);
    }
    public function sentMsg(){
        $template_id = $this->request->param('template_id');
        $openid= $this->request->param('open_id');
        $data = json_decode($this->request->param('content'),true);

        //echo $this->request->param('content');exit;
        $tokenArr = $this->getToken();
        // 示例数据
//        $openid = "oQ8HH5szLocgW0UjiRIuppMbkcFQ";
//        $template_id = "VZo9UR7DCm6phxYrnHvf8729SD8Unsnoq_EZfM1gQCk"; // 替换为你的模板 ID
        $url = ""; // 跳转链接（可选）

//        $data =[
//            "thing10" => ["value" => "测试门店"],
//            "thing11" => ["value" => "项目一"], // 充值金额
//            "amount2" => ["value" => "50.00"], // 订单号
//            "time4" => ["value" => date("Y-m-d H:i:s"),
//            "amount3" => ["value" => "100.00"]]
//            ];
        //$token ='91_Ncw3j6vUpxZv8jBCcGfEkoHp7hZr6VzL1H4mzUk-b7l5irXdTKWm6BT0WYv_-lFpNBgEBSHyqqeNW9e2-HchXgjL2Sz96bDn6GOC9gyI77S-FXJu8cud8WRxNKMHXXaABAMCC';

        $response = $this->sendTemplateMessage($tokenArr['access_token'],$openid, $template_id, $data, $url);
        //$response = $this->sendSubscriptionMessage($tokenArr['access_token'],$openid, $template_id, '', $data);
       echo json_encode($response);exit;
    }

    public function getToken(){
        $appId = self::appId;
        $appSecret = self::appSecret;
        $json=[];
        try {
            $token = file_get_contents('./token.txt');

            if($token){
                $token = json_decode($token,true);
                if($token['expires_in']>time()){
                    $json = $token;
                }else{
                    $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
                    $response = file_get_contents($token_url);

                    $json = json_decode($response, true);
                    $json['expires_in'] = time() +$json['expires_in'];
                    file_put_contents('./token.txt',json_encode($json));
                }
            }else{
                $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
                $response = file_get_contents($token_url);

                $json = json_decode($response, true);
                $json['expires_in'] = time() +$json['expires_in'];

                file_put_contents('./token.txt',json_encode($json));
            }
        }catch (\Exception $e){
            $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            $response = file_get_contents($token_url);

            $json = json_decode($response, true);
            $json['expires_in'] = time() +$json['expires_in'];

            file_put_contents('./token.txt',json_encode($json));
        }

        return $json;
    }
    // 发送订阅消息
    function sendSubscriptionMessage($access_token,$openid, $template_id, $page, $data) {
        global $appid, $secret;

        //$access_token = getAccessToken($appid, $secret);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";

        $post_data = [
            "touser" => $openid, // 用户的 openid
            "template_id" => $template_id, // 模板 ID
            "page" =>'', // 点击消息后跳转的页面路径（可选）
            "data" => $data, // 消息内容
            "miniprogram_state" => "developer", // 小程序状态：正式版（formal）、体验版（trial）、开发版（developer）
            "lang" => "zh_CN" // 语言，默认 zh_CN
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);

        return json_decode($result, true);
    }
    // 发送模板消息
    function sendTemplateMessage($access_token,$openid, $template_id, $data, $url = null) {

        $api_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";

        $post_data = [
            "touser" => $openid, // 用户的 openid
            "template_id" => $template_id, // 模板 ID
            "url" => $url, // 点击消息后跳转的链接（可选）
            "data" => $data // 消息内容
        ];

        //print_r($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);

        curl_close($ch);

        return json_decode($result, true);
    }


}